package handler

import (
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	"choujiang/box_server/service"
	"choujiang/common/consts"
	"choujiang/common/models"
	"choujiang/common/utils"
	"choujiang/common/variable"
	"strconv"
	"time"
)

type AgentInfo struct {
	Wechat   string `json:"wechat"`
	GroupQr  string `json:"group_qr"`
	NickName string `json:"nick_name"`
	Avatar   string `json:"avatar"`
}

func PartyCode(c *gin.Context) {
	form := c.Request.Form
	code := form.Get("code")
	gameId := form.Get("gameId")
	dlId := form.Get("dlId")
	inviteId := form.Get("inviteId")
	if _, ok := variable.EntryBoxs[gameId]; !ok {
		utils.Error(consts.ErrUndefinedEntry, c)
		return
	}
	boxEntry := variable.EntryBoxs[gameId]
	loginInfo, err := service.CodeToUserInfo(code, &boxEntry)
	if err != nil {
		fmt.Printf("-----CodeToUserInfo err: %s", err)
		utils.Error(consts.ErrInvalidParams, c)
		return
	}
	if loginInfo.OpenId == "" {
		utils.Error(consts.ErrInvalidParams, c)
		return
	}
	user := model.GetUserByGameIdOpenId(gameId, loginInfo.OpenId)
	if user == nil {
		newUser := &model.User{
			UniqueId:    utils.GenUid(gameId, loginInfo.OpenId),
			MiniOpenId:  loginInfo.OpenId,
			MiniUnionId: loginInfo.UnionID,
			GameId:      gameId,
			ShareCode:   utils.GenUid(gameId+"_shareCode", loginInfo.OpenId),
		}
		if _, err := newUser.Insert(); err != nil {
			fmt.Printf("err %+v\n", err)
		} else {
			invite64, _ := strconv.ParseInt(inviteId, 10, 64)
			int64Id, _ := strconv.ParseInt(dlId, 10, 64)
			dlUser := model.GetDlById(int64Id)
			var parentId int64
			var parentUnique string
			if dlUser != nil {
				parentUnique = dlUser.UniqueId
				parentId = dlUser.Id
			}
			extra := &model.HzwUserExtra{
				UserId:         newUser.Id,
				UserUniqueId:   newUser.UniqueId,
				ParentId:       parentId,
				ParentUniqueId: parentUnique,
				Superior:       invite64,
			}
			if _, err := extra.Insert(); err != nil {
				fmt.Printf("-----HzwUserExtra insert err: %s", err)
			}
			if parentId != 0 {
				go func() {
					//邀请新用户给代理发送通知
					service.PrepareNotice(parentId, newUser.Id)
				}()
			}
		}
		user = newUser
	} else {
		userExtra := model.GetHzwUserExtraByUid(user.Id)
		if userExtra != nil && userExtra.ParentId == 0 {
			int64Id, _ := strconv.ParseInt(dlId, 10, 64)
			dlUser := model.GetDlById(int64Id)
			if dlUser != nil {
				userExtra.ParentId = int64Id
				if _, err := userExtra.Update(); err != nil {
					fmt.Printf("userExtra parentid err %s", err)
				}
			}
		}
	}
	//保存session key
	if err = service.SetUserSessionKey(loginInfo.OpenId, gameId, loginInfo.SessionKey); err != nil {
		fmt.Printf("SetUserSessionKey err : %+v\n", err)
	}
	fmt.Printf("-----GetUserByGameIdOpenId user: %v+", user)
	resp := &CodeApiUserResp{
		UniqueId: user.UniqueId,
		OpenId:   loginInfo.OpenId,
	}
	fmt.Printf("-----CodeApiUserResp resp: %v+", resp)
	utils.JSON(resp, c)
}

func PartySetUserInfo(c *gin.Context) {
	form := c.Request.Form
	iv := form.Get("iv")
	openId := form.Get("openId")
	encryptedData := form.Get("encryptedData")
	gameId := form.Get("gameId")
	fmt.Printf("-----PartySetUserInfo gameId: %s, openId: %s, encryptedData: %s, iv: %s\n", gameId, openId, encryptedData, iv)
	if openId == "" || encryptedData == "" || iv == "" || gameId == "" {
		utils.Error(consts.ErrInvalidParams, c)
		return
	}
	newUserInfo, err := service.ParseUserInfo(openId, gameId, encryptedData, iv, nil, "")
	if err != nil {
		fmt.Printf("newUserInfo err: %+v\n", err)
		utils.Error(consts.ErrMiniOriData, c)
		return
	}
	fmt.Printf("-----PartySetUserInfo newUserInfo: %v+", newUserInfo)
	user := model.GetUserByGameIdOpenId(gameId, newUserInfo.OpenId)
	fmt.Printf("-----PartySetUserInfo user: %v+", user)
	if user != nil {
		user.City = newUserInfo.City
		user.Province = newUserInfo.Province
		user.HeadImgUrl = newUserInfo.AvatarURL
		user.Sex = newUserInfo.Gender
		user.NickName = base64.StdEncoding.EncodeToString([]byte(newUserInfo.NickName))
		user.HeadImgUpdatedAt = time.Now().Unix()
		user.MiniUnionId = newUserInfo.UnionID
		_, err := user.Update()
		if err != nil {
			fmt.Printf("-----PartySetUserInfo user update err: %s", err)
			utils.Error(consts.ErrUserUpadteFail, c)
			return
		}
	}
	if user.NickName != "" {
		user.NickName = utils.DecodeNickName(user.NickName)
	}
	if user != nil {
		extra := model.GetHzwUserExtraByUid(user.Id)
		fmt.Printf("-----GetHzwUserExtraByUid extra: %v+", extra)
		if extra != nil {
			user.DlId = extra.ParentId
			if extra.ParentId != 0 {
				//统计用户活跃数量
				service.LogActiveUser(extra.ParentId, user.Id)
			}
		} else {
			user.DlId = 0
		}
	} else {
		user.DlId = 0
	}
	if newUserInfo.UnionID != "" {
		dlUser := model.GetDlByUnionId(newUserInfo.UnionID)
		if dlUser != nil {
			user.DlId = dlUser.Id
		}
	}
	utils.JSON(user, c)
}

/**
 获取用户的代理微信群及代理微信号
 */
func UserAgent(c *gin.Context) {
	form := c.Request.Form
	dlId := form.Get("dlId")
	int64Id, _ := strconv.ParseInt(dlId, 10, 64)
	hzwUser := model.GetDlById(int64Id)
	if hzwUser == nil {
		utils.Error(consts.ErrUndefinedAgent, c)
	}
	agentInfo := &AgentInfo{
		Wechat:   hzwUser.WechatCode,
		GroupQr:  hzwUser.PlayerGroup,
		NickName: utils.DecodeNickName(hzwUser.NickName),
		Avatar:   hzwUser.HeadImgUrl,
	}
	utils.JSON(agentInfo, c)
}
